package org.example.threadtest;

import java.util.concurrent.TimeUnit;

/**
 * 停掉线程的方法
 */
class StopThreadDemo extends Thread {
    private volatile boolean flag = true; // 需要加volatile，使flag变量可见

    @Override
    public void run() {
        System.out.println("子线程开始");
        while (flag) {
            // 执行代码
        }
        System.out.println("子线程结束");
    }

    public void stopThread() {
        this.flag = false;
    }
}

public class StopThread {
    public static void main(String[] args) throws InterruptedException {
        StopThreadDemo stopThreadDemo = new StopThreadDemo();
        stopThreadDemo.start();
        for (int i = 0; i < 10; i++) {
            System.out.println("我是主线程,i:"+ i);
            TimeUnit.SECONDS.sleep(1);
            if (i == 4) {
                stopThreadDemo.stopThread();
            }
        }
    }
}
